from typing import Sequence,Any,Optional
from APP.app.userprofile.models.user_info import UserInfo
from APP.database.mysql import async_db_session
from APP.app.userprofile.crud.profile_explicit_crud import ExplicitProfileDao
from APP.config.log_conf import log
import uuid
from APP.app.userprofile.schemas.user_profile_schema import UserTag
from APP.app.userprofile.schemas.tag_schema import TagCategory,TagType


class ProfileExplicitServices:

    @staticmethod
    async def get_user_all() -> Sequence[UserInfo]:
        """
        获取所有用户信息
        :return: 用户信息列表
        """
          
        async with async_db_session() as db:

            user_infos = await ExplicitProfileDao.get_user_all(db)
            return user_infos
    
    
    async def extract_explicit_tags(self,data:dict[str,Any]) -> list[UserTag]:
        """
        根据用户显示属性生成标签
        :param data:userinfo表所有数据
        :return: 用户标签列表
        """
        log.info(f"开始生成用户显示标签，数据量：{len(data)}")
        #先提取data中的一个字典数据
        dt = data[0]

        explicit_tags = await self._generate_tags(dt)
        
        return explicit_tags


    async def _generate_tags(self, data: dict[str, Any]) -> list[UserTag]:
        """
        生成标签字符串
        :return: 标签字符串
        """
        explicit_tags = []

        if 'age' in data:
            age_range = await self._classify_age_range(data['age'])
            explicit_tags.append(self._create_tag(
                '年龄段',
                age_range,
                TagCategory.BASICINFO,
                TagType.EXPLICIT,
                1.0,
                "user_info.age",
                {'raw_age': data['age']}
            )) 

        return explicit_tags
    
    @staticmethod
    async def _classify_age_range(age: int) -> str:
        """
        根据年龄划分年龄段
        :param age: 年龄
        :return: 年龄段标签
        """
        if age < 18:
            return "未成年"
        elif  age< 25: 
            return "18-24"
        elif  age < 35:
            return "25-34"
        elif  age < 45:
            return "35-44"
        elif  age < 55:
            return "45-54"
        elif  age < 65:
            return "55-64"
        else:
            return "65+"
    
    @staticmethod
    def _create_tag(name: str, value: Any, category: TagCategory, tag_type: TagType, confidence: float, source: str, metadata: Optional[dict[str, Any]] = None) -> UserTag:
        """创建标签对象"""
        return UserTag(
            tag_id=str(uuid.uuid4()),
            name=name,
            value=value,
            category=category,
            tag_type=tag_type,
            confidence=confidence,
            source=source,
            metadata=metadata or {}
        )

ProfileExplicitService: ProfileExplicitServices = ProfileExplicitServices()